<!DOCTYPE html>
<html debug="true">
  <head>
    <script type="text/javascript" src="../../../../../openlayers/lib/OpenLayers.js"></script>
    <script type="text/javascript" src="../../../../../ext/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="../../../../../ext/ext-all-debug.js"></script>
    <script type="text/javascript" src="../../../../lib/GeoExt.js"></script>

    <script type="text/javascript">
        var printCapabilities = {"scales":[{"name":"1:25,000","value":"25000"},{"name":"1:50,000","value":"50000"},{"name":"1:100,000","value":"100000"},{"name":"1:200,000","value":"200000"},{"name":"1:500,000","value":"500000"},{"name":"1:1,000,000","value":"1000000"},{"name":"1:2,000,000","value":"2000000"},{"name":"1:4,000,000","value":"4000000"}],"dpis":[{"name":"75","value":"75"},{"name":"150","value":"150"},{"name":"300","value":"300"}],"layouts":[{"name":"A4 portrait","map":{"width":440,"height":483},"rotation":true},{"name":"Legal","map":{"width":440,"height":483},"rotation":false}],"printURL":"http://demo.opengeo.org/geoserver/pdf/print.pdf","createURL":"http://demo.opengeo.org/geoserver/pdf/create.json"};
        
        function test_constructor(t) {
            t.plan(7);
            var log = {};
            
            var origRequest = Ext.Ajax.request;
            Ext.Ajax.request = function(req) {
                req.success.call(req.scope, {responseText: Ext.encode(printCapabilities)});
            }
            var printProvider = new GeoExt.data.PrintProvider({
                url: "PrintProvider",
                listeners: {
                    "loadcapabilities": function() {
                        log.loadcapabilities = arguments;
                    }
                }
            });
            Ext.Ajax.request = origRequest;
            
            t.eq(printProvider.customParams, {}, "customParams initialized properly.");
            t.ok(log.loadcapabilities[0] == printProvider, "printProvider passed as 1st argument of the loadcapabilities listener.");
            t.ok(log.loadcapabilities[1] == printProvider.capabilities, "capabilities passed as 2nd argument of the loadcapabilities listener.");
            t.eq(printProvider.capabilities.createURL, "http://demo.opengeo.org/geoserver/pdf/create.json", "capabilities available and createURL correct after loadcapabilities event");
            t.ok(printProvider.layout == printProvider.layouts.getAt(0), "layout set to first available layout record.");
            t.ok(printProvider.dpi == printProvider.dpis.getAt(0), "dpi set to first available dpi record.");
            t.eq(printProvider.scales.getCount(), 8, "8 scales read in properly.");
        }
        
        function test_setLayout(t) {
            t.plan(3);
            var log = {};
            var printProvider = new GeoExt.data.PrintProvider({
                capabilities: printCapabilities,
                listeners: {
                    "layoutchange": function() {
                        log.layoutchange = arguments;
                    }
                }
            });
            var layout = printProvider.layouts.getAt(1);
            printProvider.setLayout(layout);
            t.ok(printProvider.layout == layout, "layout set correctly.");
            t.ok(log.layoutchange[0] == printProvider, "printProvider passed as 1st argment of the layoutchange listener.");
            t.ok(log.layoutchange[1] == layout, "layout passed as 2nd argment of the layoutchange listener.");
        }

        function test_setDpi(t) {
            t.plan(3);
            var log = {};
            var printProvider = new GeoExt.data.PrintProvider({
                capabilities: printCapabilities,
                listeners: {
                    "dpichange": function() {
                        log.dpichange = arguments;
                    }
                }
            });
            var dpi = printProvider.dpis.getAt(1);
            printProvider.setDpi(dpi);
            t.ok(printProvider.dpi == dpi, "dpi set correctly.");
            t.ok(log.dpichange[0] == printProvider, "printProvider passed as 1st argment of the dpichange listener.");
            t.ok(log.dpichange[1] == dpi, "dpi passed as 2nd argment of the dpichange listener.");
        }
        
        function test_getAbsoluteUrl(t) {
            t.plan(2);
            
            var getAbsoluteUrl = GeoExt.data.PrintProvider.prototype.getAbsoluteUrl;
            var baseUrl = parent.location.href.substr(0, parent.location.href.indexOf("/tests/run-tests.html"));
            t.eq(getAbsoluteUrl("/foo/bar.html"), location.protocol + "//" + location.host + (location.port && ":" + location.port) + "/foo/bar.html", "Relative url converted to absolute url correctly.");
            t.eq(getAbsoluteUrl("../../../../bar.html"), baseUrl + "/bar.html", "Relative url with relative path converted to absolute url correctly.");
        }
        
        function test_print(t) {
            t.plan(1);
            var log = {};
            var printProvider = new GeoExt.data.PrintProvider({
                capabilities: printCapabilities,
                customParams: {customParam: "foo"},
                listeners: {
                    "dpichange": function() {
                        log.dpichange = arguments;
                    },
                    "beforeencodelayer": function(provider, layer) {
                        return layer.name !== "don't print me";
                    },
                    "encodelayer": function(provider, layer, encodedLayer) {
                        if (layer instanceof OpenLayers.Layer.WMS) {
                            encodedLayer.customParams = Ext.apply({
                                map_resolution: 150
                            }, encodedLayer.customParams);
                        }
                    }
                }
            });
            var printPage = new GeoExt.data.PrintPage({
                printProvider: printProvider,
                customParams: {mapTitle: "foo", comment: "bar"}
            });
            var map = new OpenLayers.Map("map");

            // layers to test all supported layer encoders
            var layers = [
                new OpenLayers.Layer.WMS("wms", "http://demo.opengeo.org/geoserver/wms", {
                    layers: ["topp:tasmania_state_boundaries","topp:tasmania_water_bodies"], format: "image/gif", vendorFoo: "bar"
                }),
                new OpenLayers.Layer.OSM("osm", null, {isBaseLayer: false}),
                new OpenLayers.Layer.TileCache("tilecache",
                    ["http://c0.labs.metacarta.com/wms-c/cache/",
                     "http://c1.labs.metacarta.com/wms-c/cache/",
                     "http://c2.labs.metacarta.com/wms-c/cache/",
                     "http://c3.labs.metacarta.com/wms-c/cache/",
                     "http://c4.labs.metacarta.com/wms-c/cache/"],
                    "basic",
                    {
                        serverResolutions: [0.703125, 0.3515625, 0.17578125, 0.087890625, 
                                            0.0439453125, 0.02197265625, 0.010986328125, 
                                            0.0054931640625, 0.00274658203125, 0.001373291015625, 
                                            0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 
                                            0.0000858306884765625, 0.00004291534423828125, 0.000021457672119140625],
                        isBaseLayer: false
                    }
                ),
                new OpenLayers.Layer.TMS(
                    "TMS",
                    "http://labs.metacarta.com/wms-c/Basic.py/",
                    {layername: 'basic', type:'png', isBaseLayer: false}
                ),
                new OpenLayers.Layer.Image(
                    "image",
                    "http://earthtrends.wri.org/images/maps/4_m_citylights_lg.gif",
                    new OpenLayers.Bounds(-180, -88.759, 180, 88.759),
                    new OpenLayers.Size(580, 288),
                    {numZoomLevels: 3, isBaseLayer: false}
                ),
                new OpenLayers.Layer.Vector("vector"),
                new OpenLayers.Layer.WMS("don't print me", "http://demo.opengeo.org/geoserver/wms",
                    {layers: "tasmania", transparent: true}, {
                        displayInLayerSwitcher: false,
                        isBaseLayer: false
                    })
            ];
            map.addLayers(layers);

            // give the vector layer a feature
            var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(1,2));
            feature.id = "f1";
            map.getLayersBy("name", "vector")[0].addFeatures([feature]);
            
            map.setCenter(new OpenLayers.LonLat(1, 2), 3);
            printPage.fit(map);
            
            // create a layer store for the legend
            var layerStore = new GeoExt.data.LayerStore({
                layers: [layers[0], layers[2]]
            });
            layerStore.getAt(1).set("legendURL", "http://trac.geoext.org/chrome/site/img/GeoExt.png");
            
            // a legend panel to test all legend encoders
            var legend = new GeoExt.LegendPanel({
                renderTo: "legend",
                layerStore: layerStore
            });

            // an overview control to test the overviewLayers encoder
            var overview = new OpenLayers.Control.OverviewMap({layers: [
                new OpenLayers.Layer.WMS("foo", "http://foo", {layers: 'mylayer'})]});
            map.addControl(overview);
            
            var origRequest = Ext.Ajax.request;
            Ext.Ajax.request = function(req) {
                log.request = req;
                var _open = window.open;
                window.open = Ext.emptyFn;
                req.success.call(req.scope, {
                    responseText: '{"getURL":"foo"}'
                });
                window.open = _open;
            }
            printProvider.print(map, [printPage], {overview: overview, legend: legend});
            Ext.Ajax.request = origRequest;
            
            var expect = {"units":"degrees","srs":"EPSG:4326","layout":"A4 portrait","dpi":75,"layers":[{"baseURL":"http://demo.opengeo.org/geoserver/wms","opacity":1,"singleTile":false,"type":"WMS","layers":["topp:tasmania_state_boundaries","topp:tasmania_water_bodies"],"format":"image/gif","styles":[""],"customParams":{"VENDORFOO":"bar", "map_resolution": 150}},{"baseURL":"http://tile.openstreetmap.org/","type":"OSM","opacity":1,"singleTile":false,"maxExtent":[-20037508.3392,-20037508.3392,20037508.3392,20037508.3392],"tileSize":[256,256],"resolutions":[156543.0339,78271.51695,39135.758475,19567.8792375,9783.93961875,4891.969809375,2445.9849046875,1222.99245234375,611.496226171875,305.7481130859375,152.87405654296876,76.43702827148438,38.21851413574219,19.109257067871095,9.554628533935547,4.777314266967774,2.388657133483887,1.1943285667419434,0.5971642833709717],"extension":"png",layer:undefined},{"baseURL":"http://c0.labs.metacarta.com/wms-c/cache/","opacity":1,"singleTile":false,"type":"TileCache","layer":"basic","maxExtent":[-180,-90,180,90],"tileSize":[256,256],"extension":"png","resolutions":[0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.000021457672119140625]},{"baseURL":"http://labs.metacarta.com/wms-c/Basic.py/","type":"TMS","opacity":1,"singleTile":false,"extension":undefined,layer:"basic","maxExtent":[-180,-90,180,90],"tileSize":[256,256],"resolutions":[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125],format:"png"},{"type":"Image","baseURL":"http://earthtrends.wri.org/images/maps/4_m_citylights_lg.gif","opacity":1,"extent":[-180,-88.759,180,88.759],"pixelSize":[580,288],"name":"image"},{"type":"Vector","styles":{"1":{"fillColor":"#ee9900","fillOpacity":0.4,"hoverFillColor":"white","hoverFillOpacity":0.8,"strokeColor":"#ee9900","strokeOpacity":1,"strokeWidth":1,"strokeLinecap":"round","strokeDashstyle":"solid","hoverStrokeColor":"red","hoverStrokeOpacity":1,"hoverStrokeWidth":0.2,"pointRadius":6,"hoverPointRadius":1,"hoverPointUnit":"%","pointerEvents":"visiblePainted","cursor":"inherit"}},"styleProperty":"_gx_style","geoJson":{"type":"FeatureCollection","features":[{"type":"Feature","id":"f1","properties":{"_gx_style":1},"geometry":{"type":"Point","coordinates":[1,2]}}]},"name":"vector","opacity":1}],"pages":[{"mapTitle":"foo","comment":"bar","center":[1,2],"scale":4000000,"rotation":0}],"customParam":"foo","legends":[{"name":"tilecache","classes":[{"name":"","icon":"http://trac.geoext.org/chrome/site/img/GeoExt.png"}]},{"name":"wms","classes":[{"name":"","icons":["http://demo.opengeo.org/geoserver/wms?FORMAT=image%2Fgif&VENDORFOO=bar&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&EXCEPTIONS=application%2Fvnd.ogc.se_xml&LAYER=topp%3Atasmania_state_boundaries&SCALE=55367980.3125","http://demo.opengeo.org/geoserver/wms?FORMAT=image%2Fgif&VENDORFOO=bar&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&EXCEPTIONS=application%2Fvnd.ogc.se_xml&LAYER=topp%3Atasmania_water_bodies&SCALE=55367980.3125"]}]}],"overviewLayers":[{"baseURL":"http://foo/","format":"image/jpeg",layers:["mylayer"],"opacity":1,"singleTile":false,styles:[""],type:"WMS", "customParams": {"map_resolution": 150}}]
};

            t.eq(log.request.jsonData, expect, "Request with encoded layers and legend is correct.");
            
            layerStore.destroy();
            printPage.destroy();
            map.destroy();
        }
    </script>
  </head>  
  <body>
    <div id="map" style="width:400px; height:300px"></div>
    <div id="legend" style="width:200px; height:300px"></div>
  </body>
</html>
